<template>
  <div class="doc-list">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px">
      <el-breadcrumb-item v-for="item in pathParam"
                          :key="item.id">
      <el-button type="text"
                 @click="changePath(item.name)"
                 :style="{'color' : item === pathParam[pathParam.length-1] ? '#ffffff' : '#6B6F7B'}">
        {{item.name}}
      </el-button>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="list-main">
      <div class="list-main-head">
        <el-upload
            class="upload-demo"
            action=""
            :http-request="handleUpload"
            :show-file-list="false"
            :auto-upload="true">
          <el-button type="primary"
                     class="button el-icon-upload2"
                     style="margin-right: 20px;  margin-left: 25px"
                    >上传</el-button>
        </el-upload>

        <el-button type="primary"
                   class="button el-icon-download"
                   @click="downloadFile">下载</el-button>
        <div class="list-main-head-right">
          <el-input id="search-key"
                    v-model="searchInput"
                    placeholder="关键字搜索"
                    style="width: 245px; height: 32px"
                    @keyup.enter.native="fileFilter"></el-input>
          <el-button type="primary"
                     class="button"
                     style="margin-right: 20px;  margin-left: 25px"
                     @click="fileFilter">搜索</el-button>
          <el-button type="info"
                     class="button"
                     style="background: #37456C;"
                     @click="clearFilter">清除筛选</el-button>
        </div>
      </div>
      <div class="list-main-body">
        <el-table
            ref="multipleTable"
            :data="fileDataPage"
            tooltip-effect="dark"
            class="table"
            @selection-change="handleSelectionChange">
            <el-table-column
                type="selection"
                width="79">
            </el-table-column>
            <el-table-column
                v-for="col in cols"
                :prop="col.prop"
                :label="col.label"
                :width="col.width"
                show-overflow-tooltip>
              <template slot-scope="scope">
               <span v-if="col.prop == 'name' || col.prop == 'note'" @dblclick="changeName(scope.$index,col.prop)">
                  <el-input v-if = "scope.$index == modifying.text.row && col.prop == modifying.text.prop"
                            v-model="scope.row[col.prop]"
                            @keyup.enter.native="changeName(scope.$index,col.prop)">
                  </el-input>
                  <span v-else>{{scope.row[col.prop]}}</span>
                </span>
                <span v-else @click="changeName(-1,col.prop)">
                  <span v-if="col.prop == 'option'">
                    <i class="el-icon-lock" style="margin-right: 22px"
                       @click="changeLimit(scope.$index)"></i>
                    <i class="el-icon-delete" style="margin-right: 22px"
                       @click="deleteFile(scope.$index)"></i>
                  </span>
                  <span v-else>
                    <el-select v-if="col.prop == 'limits' && scope.$index == modifying.limits"
                               v-model="scope.row[col.prop]" @change="changeLimit(scope.$index)">
                      <el-option
                          v-for="item in Limitoptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                    </el-select>
                    <span v-else>{{scope.row[col.prop]}}</span>
                  </span>
                </span>
              </template>
            </el-table-column>
        </el-table>
        <!-- 分页底部 -->
        <div style="display: inline;">
          <el-pagination
              background
              style="margin-top: 5px; float: right"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-size="pageSize"
              layout="total, prev, pager, next"
              :total="fileList.length"
          ></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {getDocList, getfile, uploadFile} from '@/api/api';

export default {
  name: "docList",
  computed: {
    pathParam (){
      return this.$store.state.docManage.selectList;
    }
  },
  watch: {
    pathParam: function (){
      this.getFileList();
    },
    fileList: function (){
      this.handleCurrentChange(this.currentPage);
    }
  },
  methods: {
    getFileList (){
      getDocList(this.pathParam).then(res => {
        this.fileList = res.data.result;
      }).catch(err => {
        console.log(err);
      });
    },
    handleUpload(file){
      console.log(file);
      let fd = new FormData();
      fd.append('file', file.file)// 传文件
      fd.append('path', this.pathParam);
      uploadFile(fd).then(res =>{
        console.log(res);
        if(res.data.code === 200) {
          this.$message.success('上传成功')
          console.log(res.data.result);
          this.fileList.unshift(res.data.result);
        }
      });

    },
    downloadFile(){
      console.log("下载这些文件：",this.multipleSelection);
      this.multipleSelection.forEach(item => {
        getfile({id: item.id})
            .then(function (resp) {
                const blob = new Blob([resp.data], {type: 'application/vnd.ms-excel;charset=utf-8'});
                const link = document.createElement('a'); // 创建a链接，用于下载文件
                link.download = item.name;
                link.style.display = 'none';
                link.href = URL.createObjectURL(blob);
                document.body.appendChild(link);//将标签插入body中
                link.click(); // 触发事件，下载文件
                URL.revokeObjectURL(link.href) ;// 释放掉blob对象
                document.body.removeChild(link) // 下载完成移除元素
              })
            .catch(e => {
              console.log('下载文件出错：', e);
            })
      });
    },
    changeName (index, prop){
      if (this.modifying.text.row === -1){
        this.modifying.text.row = index;
        this.modifying.text.prop = prop;
        this.modifying.text.value = this.fileDataPage[index][prop];
      }
      else {
        if (index < 0){
          index = this.modifying.text.row;
          prop = this.modifying.text.prop;
        }
        if (this.modifying.text.value !== this.fileDataPage[index][prop]){
          let key = this.fileDataPage[index].id;
          console.log(this.modifying.text.value, this.fileDataPage[index][prop]);
          //TODO 根据 this.fileDataPage[index].id 将修改文件名称的请求 post 到后端
        }
        this.modifying.text.row = -1;
        this.modifying.text.prop = "";
      }
    },
    changeLimit (index){
      if (this.modifying.limits === -1){
        this.modifying.limits = index;
      }
      else {
        let key = this.fileDataPage[index].id;
        console.log(key, this.fileDataPage[index].name);
        //TODO 根据 this.fileDataPage[index].id 将更改文件权限的请求 post 到后端
        this.modifying.limits = -1;
      }
    },
    deleteFile (index){
      console.log("delete!!",index);
      let key = this.fileDataPage[index].id;
      for (let i = 0; i < this.fileList.length; i++){
        if (this.fileList[i].id === key){
          this.fileList.splice(i, 1);
          break;
        }
      }
      //TODO 根据 this.fileDataPage[index].id 将删除文件的请求 post 到后端
    },
    changePath (key){
      let path = this.pathParam;
      for (let i = 0; i < path.length; i++){
        if (key === path[i].name)
        {
          this.$store.commit('docManage/changeselectList', path.slice(0,i+1));
        }
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    handleCurrentChange (currentPage) {
      this.currentPage = currentPage;
      let start = (currentPage - 1) * this.pageSize;
      this.fileDataPage = this.fileList.slice(start,start + this.pageSize);
    },
    clearFilter() {
      this.searchInput = "";
      this.fileFilter();
    },
    fileFilter(){
      console.log(this.searchInput);
      if (this.searchInput === ""){
        this.handleCurrentChange(this.currentPage);
        return;
      }
      this.fileDataPage = [];
      this.fileList.forEach(item => {
        if(item.name.indexOf(this.searchInput) !== -1 ||
           item.limits.indexOf(this.searchInput) !== -1){
          this.fileDataPage.push(item);
        };
      });
    }
  },
  mounted() {

  },
  data() {
    return {
      fileList : [],
      fileDataPage : [],
      searchInput: "",
      multipleSelection: [],
      currentPage : 1,
      pageSize: 10,
      fileListUpload: [],
      cols: [
        {prop: 'name', label: '文件名', width: '245'},
        {prop: 'limits', label: '权限/所有者', width: '200'},
        {prop: 'size', label: '大小', width: '185'},
        {prop: 'time', label: '修改时间', width: '276'},
        {prop: 'note', label: '备注', width: '300'},
        {prop: 'option', label: '操作', width: '147'},
      ],
      modifying : {
        text : {
          prop : "",
          value : "",
          row : -1
        },
        limits : -1
      },
      Limitoptions : [{
          value: '可读',
          label: '可读'
        }, {
          value: '可写',
          label: '可写'
        }, {
          value: '可读/可写',
          label: '可读/可写'
        }
      ]
    }
  }
}
</script>

<style>

.doc-list{
  flex-direction: column;
}

.doc-list .list-main{
  width: 1480px;
  margin-right: 20px;
  display: flex;
  background: #13192C;
  flex-wrap:  wrap;
}

.doc-list .list-main .button{
  width: 86px;
  height: 31px;
  background: #0081E2;
  border-radius: 4px;
  padding: 0;
}

.doc-list .list-main .table{
  width: 1432px;
  margin-right: 24px;
  margin-left: 24px;
}

.doc-list .list-main .list-main-head{
  display: flex;
  align-items: center;
}

.doc-list .list-main .list-main-head-right{
  display: flex;
  width: 1239px;
  height: 76px;
  justify-content:flex-end;
  align-items: center;
}

.doc-list .list-main-head-right .el-input .el-input__inner{
  width: 245px;
  height: 32px;
}

.doc-list .list-main .list-main-body{
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.doc-list .el-input__inner, .el-date-editor .el-range-input{
  color: #FFFFFF;
}

.doc-list .el-button--text{
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #FFFFFF;
  line-height: 20px;
}

/*表格表头样式*/
.doc-list .el-table__header th.el-table__cell{
  height: 48px;
}
/*表格主体样式*/
.doc-list .el-table__body td.el-table__cell{
  height: 56px;
}

/*表格主体每行高度*/
.doc-list .el-table__row {
  height: 56px;
}


</style>